package scatter.wwd.rest.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.common.dict.PublicDictEnums;
import scatter.common.pojo.form.BasePageQueryForm;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import scatter.common.rest.security.LoginUserTool;
import scatter.common.rest.validation.DictService;
import scatter.wwd.pojo.po.Activity;
import scatter.wwd.pojo.po.ActivityContent;
import scatter.wwd.pojo.po.ActivityEnrollRule;
import scatter.wwd.pojo.po.ActivityParticipate;
import scatter.wwd.pojo.vo.ActivityVo;
import scatter.wwd.pojo.vo.ActivityDetailVo;
import scatter.wwd.pojo.vo.AppActivityListVo;
import scatter.wwd.pojo.vo.AppActivityPayDetailVo;
import scatter.wwd.rest.mapper.ActivityMapper;
import scatter.wwd.rest.mapper.UserInfoMapper;
import scatter.wwd.rest.mapstruct.ActivityEnrollRuleMapStruct;
import scatter.wwd.rest.mapstruct.ActivityMapStruct;
import scatter.wwd.rest.mapstruct.ActivityParticipateMapStruct;
import scatter.wwd.rest.service.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Date 6/12/21 11:56 AM
 * @Created by ciaj.
 */
@Service
public class IMiniAppServiceImpl implements IMiniAppService {

    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private IActivityEnrollRuleService iActivityEnrollRuleService;

    @Autowired
    private IActivityParticipateService iActivityParticipateService;

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private IActivityContentService iActivityContentService;

    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private DictService dictService;




    /**
     * 填充其它属性，活动报名规则，参与状态，订单号（主要用于退款）
     * @param result
     * @param includeParticipate,如果为false订单号将为空
     */
    private void fill(IPage<AppActivityListVo> result,boolean includeParticipate){
        if (result != null && CollectionUtils.isNotEmpty(result.getRecords())) {
            List<String> activityIds = result.getRecords().stream().map(AppActivityListVo::getId).collect(Collectors.toList());
            // 活动规则
            List<ActivityEnrollRule> rules = iActivityEnrollRuleService.getByActivityIds(activityIds);
            Map<String, ActivityEnrollRule> stringActivityEnrollRuleMap = rules.stream().collect(Collectors.toMap(ActivityEnrollRule::getActivityId, v -> v));
            result.getRecords().forEach(activityVo -> activityVo.setRuleVo(ActivityEnrollRuleMapStruct.INSTANCE.poToVo(stringActivityEnrollRuleMap.get(activityVo.getId()))));

            // 参与
            Map<String, ActivityParticipate> stringActivityParticipateMap = null;
            if (includeParticipate && LoginUserTool.getLoginUser() != null) {
                List<ActivityParticipate> byActivityIdsAndUserIdAndIsQuit = iActivityParticipateService.getByActivityIdsAndUserIdAndIsQuit(activityIds, LoginUserTool.getLoginUserId(), false);
                stringActivityParticipateMap = byActivityIdsAndUserIdAndIsQuit.stream().collect(Collectors.toMap(ActivityParticipate::getActivityId,v->v));

            }


            Map<String, ActivityParticipate> finalStringActivityParticipateMap1 = stringActivityParticipateMap;
            result.getRecords().forEach(item -> {
                item.setParticipateTotal(item.getRuleVo().getCountFemale() + item.getRuleVo().getCountMale());
                item.setParticipateLimitTotal(item.getRuleVo().getIsHeadcountGenderSelf() ? (item.getRuleVo().getHeadcountMale() + item.getRuleVo().getHeadcountFemale()): item.getRuleVo().getHeadcount());
                if (finalStringActivityParticipateMap1 != null && finalStringActivityParticipateMap1.get(item.getId()) != null) {
                    item.setIsParticipate(true);
                    item.setOrderNo(finalStringActivityParticipateMap1.get(item.getId()).getOrderNo());
                }else {
                    item.setIsParticipate(false);
                }
            });

        }
    }

    @Override
    public AppActivityPayDetailVo getActivityPayDetailById(String id, PublicDictEnums.DictGender dictGender) {

        Activity activity = iActivityService.getById(id);
        ActivityEnrollRule enrollRule = iActivityEnrollRuleService.getByActivityId(id);

        AppActivityPayDetailVo appActivityPayDetailVo = new AppActivityPayDetailVo();
        appActivityPayDetailVo.setId(activity.getId());
        appActivityPayDetailVo.setTitle(activity.getTitle());
        appActivityPayDetailVo.setAddress(activity.getAddress());

        if (dictGender == PublicDictEnums.DictGender.f) {
            appActivityPayDetailVo.setTotalFee(enrollRule.getFemalePrice());
        }if (dictGender == PublicDictEnums.DictGender.m) {
            appActivityPayDetailVo.setTotalFee(enrollRule.getMalePrice());
        }

        appActivityPayDetailVo.setTitleUrl(activity.getTitleUrl());
        appActivityPayDetailVo.setStartTime(activity.getStartTime());
        appActivityPayDetailVo.setEndTime(activity.getEndTime());
        appActivityPayDetailVo.setIsNeedPayOnline(enrollRule.getIsNeedPayOnline());


        return appActivityPayDetailVo;
    }


    @Override
    public List<Map<String, Object>> getUserAlbum(String userId) {
        return userInfoMapper.getUserAlbum(userId);
    }
}
